package pro.softzhang.algo.common;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class Utils {
    public static final void printArr(int[] arr) {
        if (arr == null || arr.length == 0) {
            System.out.println("Arr: []");
            return;
        }

        System.out.print("Arr: [");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + ",");
        }
        System.out.println(arr[arr.length - 1] + "]");
    }

    public static void print2DArr(int[][] arr) {
        if (arr == null || arr.length == 0) {
            System.out.println("=== 2D Array Begin ===");
            return;
        }

        System.out.println("=== 2D Array Begin ===");
        for (int i = 0; i < arr.length; i++) {
            printArr(arr[i]);
        }
        System.out.println("=== 2D Array End ===");
    }

    public static void printLinkedList(ListNode head) {
        if(head == null) {
            System.out.print("LinkedList: []");
            return;
        }
        System.out.print("LinkedList: ");
        while (head.next != null) {
            System.out.print(head.val + ",");
            head = head.next;
        }
        System.out.println(head.val);
    }

    public static void printDoublyLinkedList(Node head) {
        if(head == null) {
            System.out.print("DLL: []");
            return;
        }
        System.out.print("DLL: ");
        while (head.next != null) {
            System.out.print(head.val + "<=>");
            head = head.next;
        }
        System.out.println(head.val);
    }

    public static void printBinaryTree(TreeNode root) {
        List<Integer> vals = new ArrayList<>();
        dfs(root, vals);
        if (vals == null || vals.size() == 0) {
            System.out.println("BinTree: []");
            return;
        }

        System.out.print("BinTree: ");
        for (int i = 0; i < vals.size() - 1; i++) {
            System.out.print(vals.get(i) + ",");
        }
        System.out.println(vals.get(vals.size() - 1));
    }

    private static void dfs(TreeNode root, List<Integer> vals) {
        if(root != null) {
            dfs(root.left, vals);
            vals.add(root.val);
            dfs(root.right, vals);
        }
    }

    /**
     * 反转单链表
     * @param head
     * @return
     */
    public static ListNode reverseLinkedList(ListNode head) {
        if(head == null) {
            return null;
        }

        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

    public static void printInJson(Object obj) {
        System.out.println(JSON.toJSONString(obj));
    }
}
